package org.xqh.utils.txt;

import org.xqh.test.yzs.devicemonitor.ExportDeviceMonitor;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @ClassName ReverseReaderFile
 * @Description TODO
 * @Author xuqianghui
 * @Date 2020/8/14 20:30
 * @Version 1.0
 */
public class ReverseReaderFile {

    private RandomAccessFile randomAccessFile = null;
    private long length = 0;
    private long index = 0;

    private ReverseReaderFile(File file) throws IOException{
        this.randomAccessFile = new RandomAccessFile(file, "r");
        this.length = this.randomAccessFile.length();
        this.index = this.length - 1;
    }

    public static ReverseReaderFile newInstance(String path) throws IOException{
        return ReverseReaderFile.newInstance(new File(path));
    }
    public static ReverseReaderFile newInstance(File file) throws IOException{
        if (file == null || !file.exists() || !file.isFile()){
            return null;
        }

        return new ReverseReaderFile(file);
    }

    /**
     * 获得文件长度
     * @auther lupingui
     * 2010-1-5 下午05:09:00
     * @return
     */
    public long getLength(){
        return this.length;
    }

    /**
     * 判断是否可继续往下读取
     * @auther lupingui
     * 2010-1-5 下午05:09:08
     * @return
     */
    public boolean next(){
        return this.index >= 0;
    }

    /**
     * 读取单行信息(去掉了回车换行)
     * @auther lupingui
     * 2010-1-5 下午05:09:34
     * @return
     * @throws IOException
     */
    public String readLine() throws IOException{
        StringBuffer line = new StringBuffer();
        char c;
        while(this.index >= 0){
            this.randomAccessFile.seek(this.index);
            c = (char)this.randomAccessFile.read();
            String lin;
            System.out.println(this.randomAccessFile.readLine());
            this.index--;
            if (c == '\n' || c == '\r'){
                if (line.length() < 1){
                    lin = this.randomAccessFile.readLine();
                    System.out.println(new String(lin.getBytes("ISO-8859-1"), "UTF-8"));
                    continue;
                }
                break;
            }
            System.out.println(String.valueOf(c));
            line.append(c);
        }

        return line == null ? null : line.reverse().toString();
    }

    public static void main(String[] args) throws IOException {
        ReverseReaderFile read = newInstance(new File(ExportDeviceMonitor.work_path+"cdrv-20200814.txt"));
        System.out.println(read.readLine());
    }

    /**
     * 关闭输出流
     * @auther lupingui
     * 2010-1-5 下午05:15:19
     * @throws IOException
     */
    public void close() throws IOException {
        this.randomAccessFile.close();
    }

}
